<template>
  <el-dialog title="编辑原子参数" :visible.sync="show" width="85%" :close-on-click-modal='false'>
    <div v-show="!previewAtomObj.showPreviewAtomDialog" v-loading="loading">
      <el-form>
        <el-form-item v-for="item in parameters" v-bind:label="item.key" :key="item.key" :label-width="aotuWidth">
        	<el-row>
        		<el-col :span="3" style="margin-right: 10px;">
	          	<el-input v-model="item.value" auto-complete="off"></el-input>
	          </el-col>
	          <el-col :span="3">
		          <el-select v-model="item.operator" style="margin-right: 15px;" v-if="data.type != 1" clearable placeholder="请选择单元格算子">
		            <el-option
		              v-for="(o, i) in operators"
		              :key="i"
		              :label="o.label"
		              :value="o.label">
		            </el-option>
		          </el-select>
	          </el-col>
	          <el-col :span="3" v-if="data.type != 1" >
	          	<el-checkbox v-model="item.is_intable">图表中是否显示</el-checkbox>
      			</el-col>
	          <el-col :span="3" v-if="data.type == 2 || data.type == 21" >
	          	<el-checkbox v-model="item.is_merge">是否合并单元格</el-checkbox>
      			</el-col>
      			<el-col :span="6" v-if="data.type == 51" >
		  			  <el-radio v-model="item.axis" label=1>标题层</el-radio>
							<el-radio v-model="item.axis" label=2>数据层</el-radio>
  					</el-col>
      			<el-col :span="8" v-if="data.type == 2 || data.type == 3 || data.type == 6 || data.type == 21">
	       			<label style="margin-right: 10px;">图表顺序:</label><el-input-number v-model="item.t_index" :min="0"></el-input-number>
	          </el-col>
	          <el-col :span="4" v-if="data.subAtoms && data.subAtoms.length > 1 && data.kind == 1 && data.type != 4 && data.type != 5" >
	          	<el-radio v-model="key_params" :label="item.key">连接主键</el-radio>
	          </el-col>
	          <el-col :span="14" v-if="data.type == 4" class="cus_dialogColor">
		  			  <el-radio v-model="item.axis" label=1>X轴</el-radio>
							<el-radio v-model="item.axis" label=2>Y轴</el-radio>
	          	<el-select v-model="item.yAxis_type" placeholder="请选择图表类型" v-if="item.axis == 2" style="margin-right: 10px;">
	          		<el-option label="柱状" value="bar"></el-option>
	          		<el-option label="折线" value="line"></el-option>
		  				</el-select>
	          	<el-select v-model="item.yAxis_color" placeholder="请选择色系" v-if="item.axis == 2" style="margin-right: 10px;">
						    <el-option
						      v-for="item in colors"
						      :key="item.value"
						      :label="item.label"
						      :value="item.value">
						    </el-option>
		  				</el-select>
		  				<el-checkbox v-model="item.show_label" v-if="item.axis == 2">是否显示数据</el-checkbox>
		  				<el-checkbox v-model="item.smart_unit" v-if="item.axis == 2">是否智能单位</el-checkbox>
	          	<!--<el-color-picker v-model="item.yAxis_color" show-alpha :predefine="predefineColors" v-if="item.axis == 2"></el-color-picker>-->
	          </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <p v-if="parameters.length == 0 && !loading">没查询到该原子的参数</p>
    </div>
    <PreviewAtom :table="atomDatas" :data="previewAtomObj.data" v-if="previewAtomObj.showPreviewAtomDialog" @closedialog="closePreview"></PreviewAtom>
    <div slot="footer" class="dialog-footer">
      <el-button @click="show = false">返回</el-button>
      <el-button type="primary" @click="parameterSubmit">确定提交</el-button>
      <el-button type="primary" @click="closePreview" v-if="previewAtomObj.showPreviewAtomDialog">关闭预览</el-button>
      <el-button type="primary" @click="previewSubmit" v-else>预览</el-button>
    </div>

  </el-dialog>
</template>
<script>
var waterfall = require("async/waterfall");
import api from "../../../api/api";
import util from "../../../common/util";
import paramHandler from '../../../../core/parameter';
import axios from "axios";
import qs from 'qs';
import PreviewAtom from "./PreviewAtom.vue";

export default {
  props: {
    data: null
  },
  components: {
    PreviewAtom
  },
  data() {
    return {
      show: true,
      loading: false,
      parameters: [],
      atomDatas: [],
      totalData: [],
      key_params: "",
      operators: [],
	    colors: [{ value: 'black',label: 'black'}, {value: 'white',label: 'white'}, {value: 'red',label: 'red'}, {value: 'yellow', label: 'yellow'}, {value: 'blue',label: 'blue'}, {value: 'green',label: 'green'}, {value: 'orange',label: 'orange'}, {value: 'purple',label: 'purple'}, {value: 'gray',label: 'gray'}, {value: 'olive',label: 'olive'}],
      isUpdate: false,
      previewAtomObj: {
        showPreviewAtomDialog: false,
        data: null
      },
      predefineColors: [
	      '#ff4500',
	      '#ff8c00',
	      '#ffd700',
	      '#90ee90',
	      '#00ced1',
	      '#1e90ff',
	      '#c71585',
	      'rgba(255, 69, 0, 0.68)',
	      'rgb(255, 120, 0)',
	      'hsv(51, 100, 98)',
	      'hsva(120, 40, 94, 0.5)',
	      'hsl(181, 100%, 37%)',
	      'hsla(209, 100%, 56%, 0.73)',
	      '#c7158577'
    	],
    	aotuWidth:'',
  		xAxis:false
    };
  },
  methods: {
    getAtomParameter() {
      const subAtoms = this.data.subAtoms;
      let promiseArr = [
        api.getAtomParameters({
          tableName: "atom_parameter",
          atom_id: this.data.id
        })
      ];
      if (this.data.kind == 1 || subAtoms.length < 2) {
        subAtoms.forEach(element => {
          var url = element.urls;
          // console.log(JSON.parse(element.fixed_req_params));
          var params = paramHandler.merge(
            JSON.parse(element.fixed_req_params),
            JSON.parse(element.auto_req_params)
          );
          console.log(params);
          promiseArr.push(
            axios({
              method: "POST",
              url: url,
              data: params
            })
          );
        });
        var that = this;
        this.loading = true;
        axios.all(promiseArr).then(
            axios.spread(function() {
              that.loading = false;
              let rets = Array.prototype.slice.call(arguments);
              var res1 = rets[0];
              var params = [];
              if (res1.ret == 0) {
                params = res1.data.dataList;
                if (params.length > 0) {
                  that.isUpdate = true;
                }
              }
              let o = {};
              for (let index = 1; index < rets.length; index++) {
                const d = rets[index];
                if (d.data.code == 0) {
                  var dataLi = d.data.data[0];
                  that.totalData.push(d.data.data);
                  o = util.extend(o, dataLi);
                }
              }
              if (o instanceof Object) {
                var pars = Object.keys(o);
                var paramets = [];
                for (var i = 0, j = pars.length; i < j; i++) {
                  var key = pars[i];
                  var obj = {
                    key: key,
                    value: ""
                  };
                  for (var index = 0; index < params.length; index++) {
                    var element = params[index];
                    if (element.name == key) {
                      obj.value = element.alias_name;
                      obj.id = element.id;
                      obj.is_intable = element.is_intable ? true : false;
                      obj.t_index = element.t_index;
                      obj.operator = element.operator;
                      obj.axis = element.axis + '';
                      obj.yAxis_color = element.yAxis_color;
                      obj.yAxis_type = element.yAxis_type;
                      obj.show_label = element.show_label ? true : false;
                      obj.smart_unit = element.smart_unit ? true : false;
                      obj.is_merge = element.is_merge ? true : false;
                    }
                    if (element.is_key) {
                      that.key_params = element.name;
                    }
                  }
                  paramets.push(obj);
                }
                that.parameters = paramets;
                //that.atomDatas = util.mergeArrays(that.parameters, realData);
              }
            })
          )
          .catch(err => {
            that.loading = false;
          });
      } else if (this.data.kind == 2) {
        var that = this;
        var tasks = [
          function(callback) {
            var url = subAtoms[0].urls;
            var params = paramHandler.merge(
              JSON.parse(subAtoms[0].fixed_req_params),
              JSON.parse(subAtoms[0].auto_req_params)
            );
            that.loading = true;
            axios({
              method: "POST",
              url: url,
              data: params
            }).then(function (res) {
              if (res.data.code == 0) {
                var data = res.data.data;
                
                if (data instanceof Array) {
                  // 取第二个原子
                  if (subAtoms[1]) {
                    var atom = subAtoms[1];
                    var promiseList = [];
                    data.forEach(element => {
                      var params = paramHandler.merge(
                        JSON.parse(atom.fixed_req_params),
                        JSON.parse(atom.auto_req_params),
                        element,
                      );
                      promiseList.push(
                        axios({
                          method: "POST",
                          url: atom.urls,
                          data: params
                        })
                      );
                    });
                    callback(null, promiseList)
                  }

                } else {
                    if (subAtoms[1]) {
                      var atom = subAtoms[1];
                      var promiseList = [];
                      var params = paramHandler.merge(
                        JSON.parse(atom.fixed_req_params),
                        JSON.parse(atom.auto_req_params),
                        data,
                      );
                      promiseList.push(
                        axios({
                          method: "POST",
                          url: atom.urls,
                          data: params
                        })
                      );
                      callback(null, promiseList)
                    }
                }
              }
            }).catch(function(err) {
              callback(err)
            })
          },
          function(arr, callback) {
              arr.unshift(      
                api.getAtomParameters({
                  tableName: "atom_parameter",
                  atom_id: that.data.id
                })
              )
              axios
                .all(arr)
                .then(
                  axios.spread(function() {
                    let rets = Array.prototype.slice.call(arguments);
                    var res1 = rets[0];
                    var params = [];
                    if (res1.ret == 0) {
                      params = res1.data.dataList;
                      if (params.length > 0) {
                        that.isUpdate = true;
                      }
                    }
                    let o = {};
                    if (rets.length > 1) {
                      let re = rets[1];
                      o = util.extend(o, re.data.data[0]);
                    }
                    for (let index = 1; index < rets.length; index++) {
                      const d = rets[index];
                      if (d.data.code == 0) {
                        that.totalData.push(d.data.data);
                      }
                    }
                    var pars = Object.keys(o);
                    var paramets = [];
                    for (var i = 0, j = pars.length; i < j; i++) {
                      var key = pars[i];
                      var obj = {
                        key: key,
                        value: ""
                      };
                      for (var index = 0; index < params.length; index++) {
                        var element = params[index];
                        if (element.name == key) {
                          obj.value = element.alias_name;
                          obj.id = element.id;
                          obj.is_intable = element.is_intable ? true : false;
                          obj.t_index = element.t_index;
                          obj.operator = element.operator;
                        	obj.axis = element.axis + '';
                      		obj.yAxis_color = element.yAxis_color;
                      		obj.yAxis_type = element.yAxis_type;
                      		obj.show_label = element.show_label ? true : false;
                      		obj.smart_unit = element.smart_unit ? true : false;
                      		obj.is_merge = element.is_merge ? true : false;
                        }
                        if (element.is_key) {
                          that.key_params = element.name;
                        }
                      }
                      paramets.push(obj);
                    }
                    callback(null, paramets)
                  })
                )
                .catch(err => {
                  that.loading = false;
                  callback(err)
                });
            
          }
        ];
        waterfall(tasks, function(err, result) {
          that.loading = false;
          if (err) {
          } else {
            that.parameters = result;
          }
        })
      }

    },
    close() {
      this.show = false;
    },
    back() {
      this.show = false;
    },
    getOpreatorList() {
      api.getOpreators().then(res => {
        this.operators = res.data;
      });
    },
    parameterSubmit() {
      let form = [];
      let check = true;
      let that = this;
      if(this.data.type == 4){
	  		let intable_params = this.parameters.filter(item => {
	        return item.is_intable;
	      });
     		let y_params = intable_params.filter(item => {
	     		return item.axis == 2
	     	});
     		let x_params = intable_params.filter(item => {
	     		return item.axis == 1
	     	});
	      if(intable_params.length > 3){
        	this.$message({ type: "warning", message: "请最多选择三组数据构成图形" });
        	return;
	      };
	     	if(y_params.length > 2 || y_params.length == 0){
        	this.$message({ type: "warning", message: "请最多选择两组数据作为y轴" });
        	return;
	     	};
     		if(x_params.length != 1){
        	this.$message({ type: "warning", message: "请选择一组数据作为x轴" });
        	return;
	     	};
      };
      if (this.data.subAtoms.length > 1 && !this.key_params && this.data.kind == 1) {
        this.$message({ type: "warning", message: "请先选择两个原子连接主键" });
        return;
      };
      for (var index = 0; index < this.parameters.length; index++) {
        var element = this.parameters[index];
        if (element.value || element.is_intable) {
          let item = [];
          item.push(this.data.id);
          item.push(element.key);
          item.push(element.value);
          item.push(element.is_intable ? true : false);
          item.push(element.key == this.key_params ? true : false);
          item.push(element.t_index || 0);
        	item.push(element.axis || 0);
          item.push(element.yAxis_color || '');
          item.push(element.yAxis_type || '');
       		item.push(element.show_label ? true : false);
          item.push(element.smart_unit ? true : false);
          item.push(element.is_merge ? true : false);
          item.push(element.operator || '');
          form.push(item);
        }
      }
      if (check) {
        if (this.isUpdate) {
          this.$message({ type: "warning", message: "原子参数不允许修改" });
        } else {
          api.batchAddAtomParameter({
	          tableName: "atom_parameter",
	          form: form
       		}).then(res => {
	          if (res.ret == 0) {
	            this.$message({ type: "success", message: "编辑参数成功" });
	            this.back();
	          }
       		}).catch(err => {
	          this.$message({ type: "error", message: "编辑参数失败" })
        	})
        }
      }
    },
    closePreview() {
      this.previewAtomObj.showPreviewAtomDialog = false;
    },
    previewSubmit() {
      if (this.data.kind == 1) {
        this.atomDatas = util.mergeArrays(
          this.parameters,
          this.totalData,
          this.key_params
        );
      } else {
        this.atomDatas = this.totalData
      }

      this.previewAtomObj.data = this.parameters;
      this.previewAtomObj.showPreviewAtomDialog = true;
    }
  },
  watch: {
    show(val) {
      if (!val) {
        this.$emit("closedialog");
      }
    }
  },
  created() {
   	console.log("created:", this.data);
    if (this.data) {
      this.key_params = this.data.key_params;
      this.getAtomParameter();
      this.aotuWidth = this.data.type == 1 ? '300px' : '150px';
    };
    this.getOpreatorList();
  },
  mounted() {}
};
</script>
<style>
.cus_input {
  width: 240px;
  margin-right: 40px;
}
.cus_dialogColor{
	display: flex;
	justify-content: flex-start;
	align-items: center;
	height: 40px;
}
</style>